<template>
  <el-tree
      :data="treeData"
      :props="defaultProps"
      :expand-on-click-node="false"
      @node-click="handleNodeClick"
      :highlight-current="true"
      :current-node-key="selectedNodeId"

  />
</template>

<script lang="ts">
import {defineComponent, ref, onMounted} from 'vue'
import {ElTree} from 'element-plus';

export default defineComponent({
  name: 'SelectTree',
  components: {
    ElTree,
  },
  setup() {
    // 树形结构数据
    const treeData = ref([
      {
        id: 1,
        label: '节点1',
        children: [
          {id: 2, label: '节点1-1'},
          {id: 3, label: '节点1-2'},
        ],
      },
      {id: 4, label: '节点2'},
      {id: 5, label: '节点3'},
    ]);

    // 默认 props 配置项
    const defaultProps = {
      children: 'children',
      label: 'label',
    };

    // 当前选中的节点 id
    const selectedNodeId = ref(null as any);//做类型断言处理

    // 处理节点点击事件
    function handleNodeClick(data: any) {
      console.log(data)
      if (data.id === selectedNodeId.value) {
        // 如果当前节点已经选中，则取消选中
        selectedNodeId.value = null;
        console.log(selectedNodeId.value, "取消选中")
      } else {
        // 否则选中当前节点
        selectedNodeId.value = data.id;
        console.log(selectedNodeId.value, "当前选中的节点")
      }
    }

    onMounted(() => {
      // 在这可以设置默认选中的节点
      // selectedNodeId.value = 1

    })

    return {
      treeData,
      defaultProps,
      selectedNodeId,
      handleNodeClick,
    };
  },
});
</script>
<style scoped lang="scss">

</style>